package com.billing.service.rest;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.billing.persistance.entities.BillingEntry;
import com.billing.service.IBillingService;


/**
 * A controller handling requests for CRUD operations on Accounts and their
 * Beneficiaries.
 */
@Controller
public class BillingEntryController {

	@Autowired
	private IBillingService billingService;
	
	//TODO Wire here a conversion service
	// http://docs.spring.io/spring/docs/3.0.0.RC2/reference/html/ch05s05.html
	
	@RequestMapping(value = "/billingentry/list", method = RequestMethod.GET)
	public @ResponseBody JSONBillingEntry[] billingEntryList() {
		
		final List<BillingEntry> list = billingService.getBillingEntries();
		
		if (list.isEmpty()){
			return new JSONBillingEntry[]{};
		}
		
		//Convert server list to JSON
		final List<JSONBillingEntry> clientList = new ArrayList<JSONBillingEntry>();
		for (BillingEntry billingEntry : list){
			clientList.add(convertToJSON(billingEntry));
		}
		
		
		JSONBillingEntry[] toReturn = clientList.toArray(new JSONBillingEntry[0]);
		return toReturn;
	}

	/**
	 * Provide the details of a bill given its Id
	 */
	@RequestMapping(value = "/billingentry/{id}", method = RequestMethod.GET)
	public @ResponseBody JSONBillingEntry findBillingEntry(@PathVariable("id") long id) {
		
		return convertToJSON(billingService.getBillingEntry(id));
	}

	private JSONBillingEntry convertToJSON(BillingEntry billingEntry) {
		
		if (billingEntry == null){
			return null;
		}
		
		final JSONBillingEntry toReturn = new JSONBillingEntry();
		
		toReturn.setDescription(billingEntry.getDescription());
		toReturn.setExecutionDate(billingEntry.getDate());
		toReturn.setAmount(billingEntry.getAmount());
		return toReturn;
	}

	
}
